package com.djf.controller;

import com.djf.service.FlowableService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Flowable流程控制器
 * 提供流程管理的REST API接口
 * 
 * @author djf
 * @date 2025/01/20
 */
@Slf4j
@RestController
@RequestMapping("/api/flowable")
@CrossOrigin(origins = "*")
public class FlowableController {

    @Autowired
    private FlowableService flowableService;

    /**
     * 部署流程定义
     * 
     * @param processName 流程名称
     * @param file BPMN文件
     * @return 部署结果
     */
    @PostMapping("/deploy")
    public ResponseEntity<Map<String, Object>> deployProcess(
            @RequestParam("processName") String processName,
            @RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            String deploymentId = flowableService.deployProcess(processName, file.getInputStream());
            result.put("success", true);
            result.put("deploymentId", deploymentId);
            result.put("message", "流程部署成功");
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            log.error("文件读取失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "文件读取失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            log.error("流程部署失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "流程部署失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 启动流程实例
     * 
     * @param request 启动请求参数
     * @return 启动结果
     */
    @PostMapping("/start")
    public ResponseEntity<Map<String, Object>> startProcess(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String processDefinitionKey = (String) request.get("processDefinitionKey");
            String businessKey = (String) request.get("businessKey");
            String startUserId = (String) request.get("startUserId");
            Map<String, Object> variables = (Map<String, Object>) request.get("variables");
            
            if (variables == null) {
                variables = new HashMap<>();
            }
            
            String processInstanceId = flowableService.startProcess(
                    processDefinitionKey, businessKey, variables, startUserId);
            
            result.put("success", true);
            result.put("processInstanceId", processInstanceId);
            result.put("message", "流程启动成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("流程启动失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "流程启动失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 完成任务
     * 
     * @param request 完成任务请求参数
     * @return 完成结果
     */
    @PostMapping("/complete-task")
    public ResponseEntity<Map<String, Object>> completeTask(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String taskId = (String) request.get("taskId");
            String userId = (String) request.get("userId");
            String comment = (String) request.get("comment");
            Map<String, Object> variables = (Map<String, Object>) request.get("variables");
            
            if (variables == null) {
                variables = new HashMap<>();
            }
            
            flowableService.completeTask(taskId, variables, comment, userId);
            
            result.put("success", true);
            result.put("message", "任务完成成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("任务完成失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "任务完成失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 查询用户待办任务
     * 
     * @param userId 用户ID
     * @return 待办任务列表
     */
    @GetMapping("/todo-tasks/{userId}")
    public ResponseEntity<Map<String, Object>> getTodoTasks(@PathVariable String userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Task> tasks = flowableService.getTodoTasks(userId);
            result.put("success", true);
            result.put("tasks", tasks);
            result.put("count", tasks.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询待办任务失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "查询待办任务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 查询用户候选任务
     * 
     * @param userId 用户ID
     * @return 候选任务列表
     */
    @GetMapping("/candidate-tasks/{userId}")
    public ResponseEntity<Map<String, Object>> getCandidateTasks(@PathVariable String userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Task> tasks = flowableService.getCandidateTasks(userId);
            result.put("success", true);
            result.put("tasks", tasks);
            result.put("count", tasks.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询候选任务失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "查询候选任务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 认领任务
     * 
     * @param request 认领请求参数
     * @return 认领结果
     */
    @PostMapping("/claim-task")
    public ResponseEntity<Map<String, Object>> claimTask(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String taskId = (String) request.get("taskId");
            String userId = (String) request.get("userId");
            
            flowableService.claimTask(taskId, userId);
            
            result.put("success", true);
            result.put("message", "任务认领成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("任务认领失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "任务认领失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 委派任务
     * 
     * @param request 委派请求参数
     * @return 委派结果
     */
    @PostMapping("/delegate-task")
    public ResponseEntity<Map<String, Object>> delegateTask(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String taskId = (String) request.get("taskId");
            String userId = (String) request.get("userId");
            
            flowableService.delegateTask(taskId, userId);
            
            result.put("success", true);
            result.put("message", "任务委派成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("任务委派失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "任务委派失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 转办任务
     * 
     * @param request 转办请求参数
     * @return 转办结果
     */
    @PostMapping("/assign-task")
    public ResponseEntity<Map<String, Object>> assignTask(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String taskId = (String) request.get("taskId");
            String userId = (String) request.get("userId");
            
            flowableService.assignTask(taskId, userId);
            
            result.put("success", true);
            result.put("message", "任务转办成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("任务转办失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "任务转办失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 查询流程定义列表
     * 
     * @return 流程定义列表
     */
    @GetMapping("/process-definitions")
    public ResponseEntity<Map<String, Object>> getProcessDefinitions() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<ProcessDefinition> processDefinitions = flowableService.getProcessDefinitions();
            result.put("success", true);
            result.put("processDefinitions", processDefinitions);
            result.put("count", processDefinitions.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询流程定义失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "查询流程定义失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 查询历史流程实例
     * 
     * @param processInstanceId 流程实例ID
     * @return 历史流程实例
     */
    @GetMapping("/historic-process/{processInstanceId}")
    public ResponseEntity<Map<String, Object>> getHistoricProcessInstance(
            @PathVariable String processInstanceId) {
        Map<String, Object> result = new HashMap<>();
        try {
            HistoricProcessInstance historicProcessInstance = 
                    flowableService.getHistoricProcessInstance(processInstanceId);
            result.put("success", true);
            result.put("historicProcessInstance", historicProcessInstance);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询历史流程实例失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "查询历史流程实例失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 查询历史任务列表
     * 
     * @param processInstanceId 流程实例ID
     * @return 历史任务列表
     */

    @Autowired
    private org.flowable.engine.HistoryService historyService;

    @GetMapping("/historic-tasks/{processInstanceId}")
    public ResponseEntity<Map<String, Object>> getHistoricTasks(@PathVariable String processInstanceId) {
        Map<String, Object> result = new HashMap<>();
        try {
            /*List<HistoricTaskInstance> historicTasks =
                    flowableService.getHistoricTasks(processInstanceId);*/
            List<HistoricTaskInstance> historicTasks = historyService
                    .createHistoricTaskInstanceQuery()
                    .processInstanceId(processInstanceId) // 设置流程实例ID作为查询条件
                    .list();
            result.put("success", true);
            result.put("historicTasks", historicTasks);
            result.put("count", historicTasks.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询历史任务失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "查询历史任务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 挂起流程实例
     * 
     * @param processInstanceId 流程实例ID
     * @return 挂起结果
     */
    @PostMapping("/suspend/{processInstanceId}")
    public ResponseEntity<Map<String, Object>> suspendProcessInstance(
            @PathVariable String processInstanceId) {
        Map<String, Object> result = new HashMap<>();
        try {
            flowableService.suspendProcessInstance(processInstanceId);
            result.put("success", true);
            result.put("message", "流程实例挂起成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("流程实例挂起失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "流程实例挂起失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 激活流程实例
     * 
     * @param processInstanceId 流程实例ID
     * @return 激活结果
     */
    @PostMapping("/activate/{processInstanceId}")
    public ResponseEntity<Map<String, Object>> activateProcessInstance(
            @PathVariable String processInstanceId) {
        Map<String, Object> result = new HashMap<>();
        try {
            flowableService.activateProcessInstance(processInstanceId);
            result.put("success", true);
            result.put("message", "流程实例激活成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("流程实例激活失败: {}", e.getMessage());
            result.put("success", false);
            result.put("message", "流程实例激活失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
}